package com.wsx.sky.data.thrift;

import com.wsx.sky.data.DataSerialization;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TTransport;

import javax.xml.crypto.Data;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.data.thrift.ThriftSerialization
 * @Description: TODO
 * @date 2019/03/14
 */
public class ThriftSerialization implements DataSerialization {


    TProtocolFactory factory = new TBinaryProtocol.Factory();

    TSerializer serializer = new TSerializer(factory);
    TDeserializer deserializer = new TDeserializer(factory);

    @Override
    public byte[] serialization(String data) {
        byte[] datas = getSerial(data);
        System.out.println(new String(datas));
        byte[] olds = data.getBytes();

        String contet = deserialization(datas);
        return datas;
    }

    private byte[] getSerial(String data) {
        TtsData ttsData = new TtsData();
        ttsData.setData(data);
        ttsData.setId(101);

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            TTransport transport = new TIOStreamTransport(out);
            TBinaryProtocol tp = new TBinaryProtocol(transport);
            ttsData.write(tp);

            return out.toByteArray();
            ///return serializer.serialize(ttsData);
        } catch (TException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("thrift ser error");
    }

    @Override
    public String deserialization(byte[] datas) {
        try {
            TtsData ttsData = new TtsData();
            ByteArrayInputStream in = new ByteArrayInputStream(datas);
            TTransport transport = new TIOStreamTransport(in);
            TBinaryProtocol protocol = new TBinaryProtocol(transport);
            ttsData.read(protocol);
            ///deserializer.deserialize(ttsData, datas);
            return ttsData.getData();
        } catch (TException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("thrift des error");
    }
}
